import React, { useState, useEffect } from 'react';
import { Card, Table, Switch, Button, Modal, Form, Input, Space, Tag } from 'antd';
import { EditOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { useElectronAPI } from '../hooks/useElectronAPI';

const PlatformsPage: React.FC = () => {
  const [platforms, setPlatforms] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingPlatform, setEditingPlatform] = useState<any>(null);
  const [form] = Form.useForm();

  const electronAPI = useElectronAPI();

  useEffect(() => {
    loadPlatforms();
  }, []);

  const loadPlatforms = async () => {
    setLoading(true);
    try {
      const data = await electronAPI.getPlatforms();
      setPlatforms(data);
    } catch (error) {
      console.error('Failed to load platforms:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleToggle = async (platform: any, enabled: boolean) => {
    try {
      // 更新平台启用状态
      const updatedPlatform = { ...platform, enabled };
      await electronAPI.addPlatform(updatedPlatform);
      await loadPlatforms();
    } catch (error) {
      console.error('Failed to update platform:', error);
    }
  };

  const handleAdd = () => {
    setEditingPlatform(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (platform: any) => {
    setEditingPlatform(platform);
    form.setFieldsValue(platform);
    setModalVisible(true);
  };

  const handleDelete = async (platformId: string) => {
    try {
      await electronAPI.removePlatform(platformId);
      await loadPlatforms();
    } catch (error) {
      console.error('Failed to delete platform:', error);
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();
      const platform = editingPlatform 
        ? { ...editingPlatform, ...values }
        : { ...values, id: Date.now().toString() };
      
      await electronAPI.addPlatform(platform);
      setModalVisible(false);
      await loadPlatforms();
    } catch (error) {
      console.error('Failed to save platform:', error);
    }
  };

  const columns = [
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      render: (icon: string) => <span style={{ fontSize: 24 }}>{icon}</span>,
    },
    {
      title: '平台名称',
      dataIndex: 'displayName',
      key: 'displayName',
    },
    {
      title: '平台ID',
      dataIndex: 'name',
      key: 'name',
      render: (name: string) => <Tag>{name}</Tag>,
    },
    {
      title: '状态',
      key: 'enabled',
      render: (_: any, record: any) => (
        <Switch
          checked={record.enabled}
          onChange={(checked) => handleToggle(record, checked)}
        />
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          />
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      <Card
        title="平台管理"
        extra={
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            添加平台
          </Button>
        }
      >
        <Table
          columns={columns}
          dataSource={platforms}
          loading={loading}
          rowKey="id"
          pagination={false}
        />
      </Card>

      <Modal
        title={editingPlatform ? '编辑平台' : '添加平台'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="平台名称"
            name="displayName"
            rules={[{ required: true, message: '请输入平台名称' }]}
          >
            <Input placeholder="例如：抖音" />
          </Form.Item>
          <Form.Item
            label="平台ID"
            name="name"
            rules={[{ required: true, message: '请输入平台ID' }]}
          >
            <Input placeholder="例如：douyin" />
          </Form.Item>
          <Form.Item
            label="图标"
            name="icon"
            rules={[{ required: true, message: '请输入图标' }]}
          >
            <Input placeholder="例如：🎵" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default PlatformsPage;
